<template class="dark">
	<div>
		<div
				style="position: fixed; z-index: 10; flex-direction: column; background: white; width: 100%; margin-top: -32px;">
			<h1 style="margin-top: 40px" class="header-text">活动管理</h1>
			<div>

				<div class="search-bar">
					<el-input
							placeholder="输入活动名称搜索活动"
							v-model="searchQuery"
							@input="handleInput"
					>
					</el-input>
				</div>
			</div>
			<el-button type="primary" @click="addActivityDialogVisible = true">添加活动
				<el-icon style="margin-left: 10px;">
					<CirclePlusFilled/>
				</el-icon>
			</el-button>
			<el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除
				<el-icon style="margin-left: 10px;">
					<RemoveFilled/>
				</el-icon>
			</el-button>
			<el-pagination
					style="margin-left: 50%;margin-top: -30px"
					v-model:current-page="currentPage"
					v-model:page-size="pageSize"
					:page-sizes="[10, 20, 50, 100]"
					layout="sizes, prev, pager, next"
					:total="totalCount"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
			/>
		</div>
		<!-- 添加活动的对话框 -->
		<el-dialog
				title="添加活动"
				v-model="addActivityDialogVisible"
				width="50%"
				:before-close="handleDialogClose"
		>
			<el-form
					:model="formData"
					:rules="rules"
					ref="activityForm"
					label-width="120px"
			>
				<el-form-item label="活动编号" prop="aid">
					<el-input v-model="formData.aid" :disabled="editStatus"></el-input>
				</el-form-item>
				<el-form-item label="活动名称" prop="aname">
					<el-input v-model="formData.aname"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="did">
					<el-input v-model="formData.did"></el-input>
				</el-form-item>
				<el-form-item label="学生学号" prop="sid">
					<el-input v-model="formData.sid"></el-input>
				</el-form-item>
				<el-form-item label="学生姓名" prop=" sname">
					<el-input v-model="formData.aname"></el-input>
				</el-form-item>
				<el-form-item label="活动主类型" prop="type">
					<el-select v-model="formData.type" placeholder="请选择主查询类型">
						<el-option label="创造能力" value="创造能力"></el-option>
						<el-option label="文体能力" value="文体能力"></el-option>
						<el-option label="社会实践能力" value="社会实践能力"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="活动补充类型" prop="types">
					<el-input v-model="formData.types"></el-input>
				</el-form-item>
				<el-form-item label="加分证明图片" prop="url">
					<el-input v-model="formData.url"></el-input>
				</el-form-item>
				<el-form-item label="活动时间" prop="date">
					<el-date-picker
							v-model="formData.date"
							type="datetime"
							placeholder="选择活动时间"
							clearable="clearable"
							style="width: 100%;"
					></el-date-picker>
				</el-form-item>
				<el-form-item label="学生班级" prop="sclass">
					<el-input v-model="formData.sclass"></el-input>
				</el-form-item>
				<el-form-item label="自定义信息1" prop="remessage1">
					<el-input v-model="formData.remessage1"></el-input>
				</el-form-item>
				<el-form-item label="自定义信息2" prop="remessage2">
					<el-input v-model="formData.remessage2"></el-input>
				</el-form-item>
				<el-form-item label="自定义信息3" prop="remessage3">
					<el-input v-model="formData.remessage3"></el-input>
				</el-form-item>
				<el-form-item label="自定义信息4" prop="remessage4">
					<el-input v-model="formData.remessage4"></el-input>
				</el-form-item>
				<el-form-item label="自定义信息5" prop="remessage5">
					<el-input v-model="formData.remessage5"></el-input>
				</el-form-item>
				<div class="dialog-footer" slot="footer">
					<el-button @click="addActivityDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmit('activityForm')">
						提交
					</el-button>
				</div>
			</el-form>
		</el-dialog>

		<!-- 活动列表 -->
		<el-table :data="paginatedData" style="width: 100%; top:180px;" @row-click="handleRowClick"
							@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column prop="aid" label="活动编号" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.aid)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="aname" label="活动名" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.aname)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="type" label="主查询类型" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.type)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="types" label="副查询类型" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.types)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="date" label="活动时间" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.date)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="stu" label="学号" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.stu)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="sclass" label="班级" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.sclass)"></span>
				</template>
			</el-table-column>
			<el-table-column prop="did" label="部门编号" style="width: 12.5%">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.did)"></span>
				</template>
			</el-table-column>
			<el-table-column label="操作">
				<template #default="{ row }">
					<el-button type="danger" size="small" @click.stop="handleDelete(row.aid)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>import AxiosService from '@/plugins/Axios.js';
import {ElMessage, ElDialog} from 'element-plus';
import {CirclePlusFilled, RemoveFilled} from "@element-plus/icons-vue";

export default {
	components: {
		RemoveFilled,
		CirclePlusFilled
	},
	data() {
		return {
			addActivityDialogVisible: false,
			formData: {
				aid: '',
				aname: '',
				did: '',
				sid: '',
				sname: '',
				type: '',
				types: '',
				url: '',
				date: '',
				stu: '',
				sclass: '',
				remessage1: '',
				remessage2: '',
				remessage3: '',
				remessage4: '',
				remessage5: '',
			},
			rules: {
				aname: [{
					required: true,
					message: '活动名不能为空',
					trigger: 'blur'
				}],
				type: [{
					required: true,
					message: '请选择主查询类型',
					trigger: 'change'
				}],
				date: [{
					required: true,
					message: '请选择活动时间',
					trigger: 'change'
				}],
				did: [{
					required: true,
					message: '部门编号不能为空',
					trigger: 'blur'
				}],
				stu: [{
					required: true,
					message: '学号不能为空',
					trigger: 'blur'
				}],
				sclass: [{
					required: true,
					message: '班级不能为空',
					trigger: 'blur'
				}],
			},
			multipleSelection: [],
			activitiesIDs: [],
			activities: '',
			paginatedActivity: [],
			currentPage: 1,
			pageSize: 10,
			totalCount: 0,
			loading: false,
			searchQuery: '',
			editStatus: false,
			originalAid: '',
			selectedActivity: '',
		};
	},
	async created() {
		await this.fetchActivities();
	},
	computed: {
		paginatedData() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			return this.paginatedActivity.slice(start, end);
		},
	},
	mounted() {
		this.fetchActivities();
	},
	methods: {
		async handleRowClick(row) {
			if (row) {
				this.editStatus = true;
				this.originalAid = row.aid;
				this.selectedActivity = {...row};
				this.formData = {...row}; // Load selected row data to form
				this.addActivityDialogVisible = true;
			}
		},
		async fetchActivities() {
			try {
				const response = await AxiosService.fetchAllActivities();
				this.paginatedActivity = response;
				this.activities = response.reverse();
				this.totalCount = response.length;
				this.activitiesIDs = this.activities.map(activity => activity.aid);
			} catch (error) {
				console.error('Error fetching activities:', error);
			} finally {
				this.loading = false;
			}
		},
		async handleSubmit(formName) {
			if (this.editStatus) {
				await this.handleEditSubmit(formName)
			} else {
				try {
					await AxiosService.addActivity(this.formData);
					ElMessage.success('活动添加成功');
					await this.fetchActivities();
					this.addActivityDialogVisible = false;
					this.handleReset(formName);
				} catch (error) {
					ElMessage.error('活动添加失败，请重试');
					console.error('Error adding activity:', error);
				}
			}
		},
		async handleBatchDelete() {
			try {
				const deletePromises = this.multipleSelection.map(activity => AxiosService.deleteActivity(activity.aid));
				await Promise.all(deletePromises);
				this.activities = this.activities.filter(activity => !this.multipleSelection.includes(activity));
				this.totalCount -= this.multipleSelection.length; // 更新总条数
				this.multipleSelection = []; // 清空选中
				this.$message({
					type: 'success',
					message: '批量删除成功!'
				});
				await this.fetchActivities()
			} catch (error) {
				console.error('Error batch deleting activity:', error);
				this.$message({
					type: 'error',
					message: '批量删除失败，请重试!'
				});
			}
		},
		async handleDelete(aid) {
			try {
				await AxiosService.deleteActivity(aid);
				ElMessage.success('活动删除成功');
				await this.fetchActivities();
			} catch (error) {
				ElMessage.error('活动删除失败，请重试');
				console.error('Error deleting activity:', error);
			}
		},
		async handleEditSubmit() {
			try {
				// 调用更新活动的API，这里假设 AxiosService.updateActivity 存在且能正确处理更新
				await AxiosService.updateActivity(this.formData);
				ElMessage.success('活动修改成功');
				await this.fetchActivities(); // 更新列表数据
				this.addActivityDialogVisible = false;
				this.handleReset('activityForm');
			} catch (error) {
				ElMessage.error('活动修改失败，请重试');
				console.error('Error editing activity:', error);
			}
		},
		handleDialogClose() {
			this.handleReset('activityForm');
		},
		handleReset() {
			this.addActivityDialogVisible = false
			this.editStatus = false
			this.formData = Object.assign({}, {
				aid: '',
				aname: '',
				type: '',
				types: '',
				date: '',
				did: '',
				stu: '',
				sclass: '',
				remessage1: '',
				remessage2: '',
				remessage3: '',
				remessage4: '',
				remessage5: '',
			});
		},
		handleSizeChange(val) {
			this.pageSize = val;
			this.currentPage = 1;
		},
		handleCurrentChange(val) {
			this.currentPage = val;
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		handleInput() {
			// Perform exact matching search
			const results = this.activities.filter(activity => {
				const searchString = `${activity.aname}${activity.aid} ${activity.type}`;
				return searchString.includes(this.searchQuery);
			});
			// Assuming you want to sort by the length of matching characters
			results.sort((a, b) => {
				const aMatchLength = this.calculateMatchLength(a);
				const bMatchLength = this.calculateMatchLength(b);
				return bMatchLength - aMatchLength;
			});
			this.paginatedActivity = results;
		},
		calculateMatchLength(activity) {
			const searchString = `${activity.aname}${activity.aid} ${activity.type}`;
			const matchIndex = searchString.indexOf(this.searchQuery);
			if (matchIndex !== -1) {
				return this.searchQuery.length;
			}
			return 0;
		},
		escapeRegExp(string) {
			return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
		},
		highlightMatch(text) {
			if (typeof text !== 'string') {
				text = String(text); // Convert non-string values to strings
			}
			if (!this.searchQuery) return text;
			const regex = new RegExp(this.escapeRegExp(this.searchQuery), 'gi');
			return text.replace(regex, (match) => `<span style="color: #ff00f3; font-weight: bolder">${match}</span>`);
		},
	},
};
</script>

<style scoped>
.search-bar {
	margin-bottom: 20px;
}

.dialog-footer {
	text-align: right;
}

.header-text {
	background-clip: padding-box;
	display: flex;
	flex-direction: column;
	float: left;
	background: -webkit-linear-gradient(315deg, #3f9dfd 15%, #f36b6b);
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
	color: transparent;
	font-weight: bolder;
}
</style>
